<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text to Speech</title>
</head>
<body>
<h1>Text to Speech</h1>

<!-- 输入框 -->
<label for="sourceIP">Source IP:</label>
<input type="text" id="sourceIP" placeholder="Enter source IP">
<br><br>

<label for="destinationIP">Destination IP:</label>
<input type="text" id="destinationIP" placeholder="Enter destination IP">
<br><br>

<label for="textToConvert">Text to Convert:</label>
<textarea id="textToConvert" placeholder="Enter text"></textarea>
<br><br>

<!-- 按钮 -->
<button id="convertButton">Convert to Speech</button>
<br><br>

<!-- 音频播放 -->
<audio id="audioPlayer" controls></audio>

<script>
    document.getElementById('convertButton').addEventListener('click', async () => {
        // 获取用户输入
        const sourceIP = document.getElementById('sourceIP').value;
        const destinationIP = document.getElementById('destinationIP').value;
        const textToConvert = document.getElementById('textToConvert').value;

        // 检查输入是否为空
        if (!sourceIP || !destinationIP || !textToConvert) {
            alert('Please fill in all fields!');
            return;
        }

        // 构造请求数据
        const requestData = {
            sourceIP: sourceIP,
            destinationIP: destinationIP,
            text: textToConvert
        };

        try {
            // 发起 POST 请求
            const response = await fetch('/api/stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            // 解析返回数据
            const result = await response.json();
            if (result.code === 1) {
                console.log(result.code)
                console.log(result.data)
                const audioDataBase64  = result.data.streamData;

                // 将 Base64 字符串解码为二进制
                const byteArray = new Uint8Array(atob(audioDataBase64).split("").map(char => char.charCodeAt(0)));

                // 将字节流转换为 Blob
                const audioBlob = new Blob([byteArray], { type: 'audio/wav' });

                // 生成可播放的音频 URL
                const audioUrl = (window.URL || webkitURL).createObjectURL(audioBlob);

                // 播放音频
                const audioPlayer = document.getElementById('audioPlayer');
                audioPlayer.controls = true;
                audioPlayer.src = audioUrl;
                audioPlayer.play();
            } else {
                alert(`Error: ${result.message}`);
            }
        } catch (error) {
            console.error('Error occurred:', error);
            alert('An error occurred: ' + error.message);
        }
    });
</script>
</body>
</html>
